﻿using Microsoft.Extensions.Logging;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using QuickGet.Core.Models;
using QuickGet.Core.Stores;

namespace QuickGet.Core.Services
{
    public class NugetSourceRepositoryResolver : INugetSourceRepositoryResolver
    {
        protected virtual ILogger _logger { get; set; }
        protected virtual IPackageSourceStore _store { get; set; }

        public NugetSourceRepositoryResolver(
            ILogger<NugetSourceRepositoryResolver> logger,
            IPackageSourceStore store)
        {
            _logger = logger;
            _store = store;
        }

        public async Task<SourceRepository?> GetRepository(string name, CancellationToken cancellationToken)
        {
            var source = await _store.GetAsync(name, cancellationToken);

            if (source is null)
            {
                _logger.LogDebug("Package source '{PackageSourceName}' is not configured", name);
                return null;
            }

            return Repository.Factory.GetCoreV3(source.Source);
        }
    }
}
